using System.Linq;
using BLL.Utils;
using DAL.File;
using DAL.SecureStore;

namespace BLL.Model
{
    public class LoginManager
    {
        protected IFileAccess Fs = new FileAccess();
        protected ISecureStore SecureStore = new LocalUserSecureStore();
        public ProfileManager ProfileManager { get; private set; }

        public bool IsLoggedIn { get; private set; }

        public void Login(string username, string password, bool isNew)
        {
            ProfileManager = ProfileManager.Create(Fs.SharedRoot, username, password, Fs, isNew);
            IsLoggedIn = ProfileManager != null;

            if (ProfileManager != null && !ProfileManager.Profile.DoNotUseAutoLogin)
                AutoLoginHelper.SetAutoLoginInfo(SecureStore, new AutoLoginInfo { Username = username, Password = password });
        }

        public string[] GetUserProfiles()
        {
            return Fs.GetFolderContents(Fs.SharedRoot, true).Select(x => x.Replace(Fs.SharedRoot, "")).ToArray();
        }

        public void TryAutoLogin()
        {
            var autoLoginInfo = AutoLoginHelper.GetAutoLoginInfo(SecureStore);
            if (autoLoginInfo != null)
                Login(autoLoginInfo.Username, autoLoginInfo.Password, false);
        }

        public void SaveProfile()
        {
            if (ProfileManager.Profile.DoNotUseAutoLogin)
                AutoLoginHelper.ClearAutoLoginInfo(SecureStore);

            ProfileManager.Save();
        }
    }
}